import { errorModal } from './util';
import { config } from '../config/index';
// import wxLogin from './wxLogin'
import wxApi from './wxApi';

// const app = getApp();
export default {
  basic: {
    BASE_URL: config.BASE_URL,
    tokenErrCode: ['500'], // token失效code
  },

  /**
   * get请求
   * */
  get({ url, data = {},loginType, options = {}, headers = {} }) {
    return this.request({
      url,
      data,
      loginType,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: wx.getStorageSync('Authorization') || '',
        'tenant-id': wx.getStorageSync('tenantId'),
        ...headers,
      },
      method: 'GET',
      useBaseUrl: true, // 使用BaseUrl
      showErr: true,
      ...options,
    });
  },

  /**
   * post 请求
   * */
  post({ url, data = {},loginType, options = {}, headers = {} }) {
    return this.request({
      url,
      data,
      loginType,
      header: {
        'Content-Type': 'application/json',
        Authorization: wx.getStorageSync('Authorization') || '',
        'tenant-id': wx.getStorageSync('tenantId'),
        ...headers,
      },
      method: 'POST',
      useBaseUrl: true, // 使用BaseUrl
      showErr: true, // toast提示报错
      ...options,
    });
  },

  /**
   * postGet请求
   * */
  postGet({ url, data = {}, options = {} }) {
    return this.request({
      url,
      data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: wx.getStorageSync('Authorization') || '',
        'tenant-id': wx.getStorageSync('tenantId'),
      },
      method: 'POST',
      useBaseUrl: true, // 使用BaseUrl
      showErr: true, // toast提示报错
      ...options,
    });
  },
  /**
   * request
   * */
  request(options) {
    return new Promise(async (resolve, reject) => {
      const { url, useBaseUrl, showErr,loginType } = options;
      // eslint-disable-next-line no-param-reassign
      options.url = useBaseUrl ? this.basic.BASE_URL + url : url;

      // const { data: reqData, url: reqUrl } = options;
      // console.log('请求接口',reqUrl)
      // console.log('请求参数',reqData)

      try {
        const { data: resData, statusCode } = await wxApi('request', options);
        if (statusCode !== 200) {
          // 服务端不通
          showErr && errorModal(resData && resData.msg ? resData.msg : '服务端异常');
          return reject(resData.msg);
        }
        if (resData.code === 0) {
          // 后端接口成功标识
          resolve(resData.data);
        } else {
          if(resData.code == 401){
            if(!loginType){
                wxApi('redirectTo', { url: '/pages/login/login' });
                this.clearStorageSync();
            }
          }else{
            showErr &&
            errorModal(resData.msg || '服务端异常').then(() => {     
              if (this.basic.tokenErrCode.includes(resData.code)) {
                // token失效code，都跳到登录页
                wxApi('redirectTo', { url: '/pages/login/login' });
                this.clearStorageSync();
              }
            });
          }
          reject(resData.msg);
        }
      } catch (err) {
        let errmsg = err.errMsg;
        errmsg = errmsg === 'request:fail timeout' ? '请求超时' : errmsg;
        showErr && errorModal(errmsg);
        reject(errmsg);
      }
    });
  },

  /**
   * 尝试静默登录
   * */
  async tryLogin() {
    this.clearStorageSync();
    // await wxLogin()
    await this.confirmReload();
    // const url = getCurrentPageUrl()
    // wxApi('redirectTo', { url })
    wxApi('redirectTo', { url: '/pages/login/login' });
  },

  /**
   * 清空缓存
   * */
  clearStorageSync() {
    // app.globalData.selectTaskId = '';
    // app.globalData.taskInfo = {
    //   // 选中的计划任务
    //   taskId: '', // 计划id
    //   planId: '', // 任务id
    //   taskOrgId: '', // 当前任务机构id
    //   taskOrgName: '', // 任务机构
    //   planName: '', // 计划名称
    //   screenTypeNames: [], // 筛查项集合
    //   userScreenTypeNames: [],
    // };
    // app.globalData.permission = [];
    // app.globalData.userInfo = {
    //   // 个人账号信息
    //   account: '',
    //   orgName: '',
    //   realName: '',
    //   orgId: '',
    // };
    // wx.setStorageSync('openId', '');
    wx.setStorageSync('Authorization', '');
  },

  /**
   * 确认重载当前页面
   * */
  confirmReload() {
    return new Promise(async (resolve, reject) => {
      const res = await wxApi('showModal', { content: '重新加载页面？' });
      if (res.confirm) {
        resolve();
      } else if (res.cancel) {
        reject();
      }
    });
  },
};
